/**
 * Zustand Global State Store
 * 全局客户端状态管理
 *
 * 用途:
 * - UI状态 (侧边栏折叠、主题等)
 * - 用户会话信息
 * - 临时表单数据
 * - 全局通知/消息队列
 *
 * 注意: 服务器数据状态由React Query管理
 */

import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'

// ============================================
// State Type Definitions
// ============================================

interface User {
  id: number
  username: string
  email: string
  roles: string[]
}

interface AppState {
  // UI状态
  sidebarCollapsed: boolean
  theme: 'light' | 'dark'

  // 用户状态
  user: User | null
  isAuthenticated: boolean

  // 全局加载状态
  globalLoading: boolean
  globalLoadingMessage: string

  // 面包屑导航
  breadcrumbs: Array<{ label: string; path?: string }>
}

interface AppActions {
  // UI操作
  toggleSidebar: () => void
  setSidebarCollapsed: (collapsed: boolean) => void
  setTheme: (theme: 'light' | 'dark') => void

  // 用户操作
  setUser: (user: User | null) => void
  login: (user: User) => void
  logout: () => void

  // 加载状态操作
  setGlobalLoading: (loading: boolean, message?: string) => void

  // 面包屑操作
  setBreadcrumbs: (breadcrumbs: Array<{ label: string; path?: string }>) => void

  // 重置状态
  reset: () => void
}

type Store = AppState & AppActions

// ============================================
// Initial State
// ============================================

const initialState: AppState = {
  sidebarCollapsed: false,
  theme: 'light',
  user: null,
  isAuthenticated: false,
  globalLoading: false,
  globalLoadingMessage: '',
  breadcrumbs: [],
}

// ============================================
// Zustand Store
// ============================================

export const useStore = create<Store>()(
  devtools(
    persist(
      (set) => ({
        // State
        ...initialState,

        // Actions
        toggleSidebar: () =>
          set((state) => ({ sidebarCollapsed: !state.sidebarCollapsed }), false, 'toggleSidebar'),

        setSidebarCollapsed: (collapsed) =>
          set({ sidebarCollapsed: collapsed }, false, 'setSidebarCollapsed'),

        setTheme: (theme) => set({ theme }, false, 'setTheme'),

        setUser: (user) =>
          set({ user, isAuthenticated: !!user }, false, 'setUser'),

        login: (user) =>
          set({ user, isAuthenticated: true }, false, 'login'),

        logout: () =>
          set({ user: null, isAuthenticated: false }, false, 'logout'),

        setGlobalLoading: (loading, message = '') =>
          set({ globalLoading: loading, globalLoadingMessage: message }, false, 'setGlobalLoading'),

        setBreadcrumbs: (breadcrumbs) =>
          set({ breadcrumbs }, false, 'setBreadcrumbs'),

        reset: () => set(initialState, false, 'reset'),
      }),
      {
        name: 'insight-app-storage', // localStorage key
        partialize: (state) => ({
          // 只持久化这些字段
          sidebarCollapsed: state.sidebarCollapsed,
          theme: state.theme,
          user: state.user,
          isAuthenticated: state.isAuthenticated,
        }),
      }
    ),
    {
      name: 'InsightAppStore', // DevTools name
      enabled: import.meta.env.DEV, // 仅开发环境启用
    }
  )
)

// ============================================
// Selector Hooks (推荐用法,避免不必要的重渲染)
// ============================================

/**
 * UI选择器
 */
export const useUIState = () =>
  useStore((state) => ({
    sidebarCollapsed: state.sidebarCollapsed,
    theme: state.theme,
    toggleSidebar: state.toggleSidebar,
    setSidebarCollapsed: state.setSidebarCollapsed,
    setTheme: state.setTheme,
  }))

/**
 * 用户选择器
 */
export const useUserState = () =>
  useStore((state) => ({
    user: state.user,
    isAuthenticated: state.isAuthenticated,
    login: state.login,
    logout: state.logout,
  }))

/**
 * 加载状态选择器
 */
export const useLoadingState = () =>
  useStore((state) => ({
    globalLoading: state.globalLoading,
    globalLoadingMessage: state.globalLoadingMessage,
    setGlobalLoading: state.setGlobalLoading,
  }))

/**
 * 面包屑选择器
 */
export const useBreadcrumbs = () =>
  useStore((state) => ({
    breadcrumbs: state.breadcrumbs,
    setBreadcrumbs: state.setBreadcrumbs,
  }))
